/*
Copyright (c) 2014, Rick Wilson
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of 'Taareekah' nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

package worldgeneration;

import worldgeneration.TerrainParameters;
import worldgeneration.AbstractMap;
import worldgeneration.WorldGenerator;

import java.io.DataOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.io.FileWriter;
import parameters.*;
/**
 *
 * @author rick
 */
/*
 *
            FileWriter o = new FileWriter(filename);
            for (int i = 0; i < size; i++) {
                for (int j = 0; j < size; j++) {
                    String out = "(" + i + ", " + j + ") = " + heightData[j + (i * size)] + "; (" + Gx[i][j] + ", " + Gy[i][j] + ")";
                    o.write((int) heightData[j + (i * size)]);
                    o.write((int) Gx[i][j]);
                    o.write((int) Gy[i][j]);
                }
            }
*/
class ElevationGradientMap extends AbstractMap {
    private AbstractMap elevation;
    private double[][] Gx;
    private double[][] Gy;
    private double[] min_max_mag = new double[2];
    
    public boolean saveAsHumanReadable(String filename) throws Exception {
        if (null == filename) {
            throw new Exception("Filename must not be null");
        }
        //open the streams and send the height data to the file.
        try {
            FileWriter o = new FileWriter(filename);
            for (int i = 0; i < size; i++) {
                for (int j = 0; j < size; j++) {
                    double theta = Math.atan2(Gy[i][j], Gx[i][j]);
                    /*if (Gx[i][j] == 0.0f) {
                        theta = Math.signum(Gy[i][j]) * Math.PI.div(2.0f);
                    } else {
                        theta = Math.atan(Gy[i][j].div(Gx[i][j]));
                    }*/
                    String out = "(" + i + ", " + j + ") = " + heightData[j + (i * size)] + "; (" + Gx[i][j] + ", " + Gy[i][j] + ") Theta=" + theta + "\n";
                    o.write(out);
                }
            }

            o.close();
        } catch (FileNotFoundException e) {
            Logger.getLogger(ElevationGradientMap.class.getName()).log(Level.SEVERE, "Error opening file {0}", filename);
            return false;
        } catch (IOException e) {
            Logger.getLogger(ElevationGradientMap.class.getName()).log(Level.SEVERE, "Error writing to file {0}", filename);
            return false;
        }

        return true;
    }
    public boolean save(String filename) throws Exception {
        if (null == filename) {
            throw new Exception("Filename must not be null");
        }
        //open the streams and send the height data to the file.
        try {
            FileOutputStream fos = new FileOutputStream(filename);
            DataOutputStream dos = new DataOutputStream(fos);
            for (int i = 0; i < size; i++) {
                for (int j = 0; j < size; j++) {
                    dos.write((int) heightData[j + (i * size)]);
                    dos.write((int) Gx[i][j]);
                    dos.write((int) Gy[i][j]);
                }
            }

            fos.close();
            dos.close();
        } catch (FileNotFoundException e) {
            Logger.getLogger(ElevationGradientMap.class.getName()).log(Level.SEVERE, "Error opening file {0}", filename);
            return false;
        } catch (IOException e) {
            Logger.getLogger(ElevationGradientMap.class.getName()).log(Level.SEVERE, "Error writing to file {0}", filename);
            return false;
        }

        return true;
    }    
    private void sobel() {
        Gx = new double[size][size];   
        Gy = new double[size][size];
        resizeData(size);

        for (int i=0; i<size; i++) {
            for (int j=0; j<size; j++) {
                if (i==0 || i==size-1 || j==0 || j==size-1) {   
                    Gx[i][j] = Gy[i][j] = 0.0; // Image boundary cleared
                    setHeightAtPoint(0.0f, i, j);
                } else {
                    Gx[i][j] = elevation.getTrueHeightAtPoint(j-1,i+1) + 2.0*elevation.getTrueHeightAtPoint(j,i+1) + elevation.getTrueHeightAtPoint(j+1,i+1) - elevation.getTrueHeightAtPoint(j-1,i-1) - 2.0*elevation.getTrueHeightAtPoint(j,i-1) - elevation.getTrueHeightAtPoint(j+1,i-1);   
                    Gy[i][j] = elevation.getTrueHeightAtPoint(j+1,i-1) + 2.0*elevation.getTrueHeightAtPoint(j+1,i) + elevation.getTrueHeightAtPoint(j+1,i+1) - elevation.getTrueHeightAtPoint(j-1,i-1) - 2.0*elevation.getTrueHeightAtPoint(j-1,i) - elevation.getTrueHeightAtPoint(j-1,i+1);
                    //Gx[i][j] = elevation.getTrueHeightAtPoint(i+1,j-1) + 2.0*elevation.getTrueHeightAtPoint(i+1,j) + elevation.getTrueHeightAtPoint(i+1,j+1) - elevation.getTrueHeightAtPoint(i-1,j-1) - 2.0*elevation.getTrueHeightAtPoint(i-1,j) - elevation.getTrueHeightAtPoint(i-1,j+1);   
                    //Gy[i][j] = elevation.getTrueHeightAtPoint(i-1,j+1) + 2.0*elevation.getTrueHeightAtPoint(i,j+1) + elevation.getTrueHeightAtPoint(i+1,j+1) - elevation.getTrueHeightAtPoint(i-1,j-1) - 2.0*elevation.getTrueHeightAtPoint(i,j-1) - elevation.getTrueHeightAtPoint(i+1,j-1);   
                    //setHeightAtPoint((Math.abs(Gx[i][j]) + Math.abs(Gy[i][j])).toFloat(), i, j);
                    double g = Math.sqrt(Gx[i][j] * Gx[i][j] + Gy[i][j] * Gy[i][j]);
                    if (g < min_max_magnitude[0]) {
                        min_max_magnitude[0] = g;
                    }
                    if (g > min_max_magnitude[1]) {
                        min_max_magnitude[1] = g;
                    }
                    setHeightAtPoint(g.toFloat(), i, j);
                }
            }
        }
    }
    
    public double getMagnitudeAtPoint(int x, int y) {
        double g = Math.sqrt(Gx[x][y] * Gx[x][y] + Gy[x][y] * Gy[x][y]);
        return g;
    }
    public double getThetaAtPoint(int x, int y) {
        double theta = Math.atan2(Gy[x][y], Gx[x][y]);
        if (theta < 0.0) {
            theta += Math.PI * 2.0;
        }
        
        return theta;
    }
    public double[] getVectorAtPoint(int x, int y) {
        double[] ret = new double[2];
        ret[0] = Gx[x][y];
        ret[1] = Gy[x][y];
        return ret;
    }
    public double[] getMinMaxMagnitude() {
        return min_max_magnitude;
    }
    public void setParams(int size, long seed, WorldGenerator generator, TerrainParameters params) {
        elevation = generator.getMap("elevation");
        this.size = size;
        this.seed = seed;
    }
    
    public boolean saveAsBitmap(String filename) throws Exception {
        return true;
    }
    
    public boolean load() {
        sobel();
        saveAsHumanReadable("gradient.txt");
        return true;
    }
}
